package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import org.springframework.security.access.prepost.PreAuthorize;
import com.ruoyi.system.domain.BizBarcode;
import com.ruoyi.system.domain.dto.GenerateBarcodeRequest;
import com.ruoyi.system.service.IBizBarcodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/system/barcode")
public class BizBarcodeController extends BaseController
{
    @Autowired
    private IBizBarcodeService bizBarcodeService;

    @Autowired
    private com.ruoyi.web.support.SupplierContext supplierContext;

    @PreAuthorize("@ss.hasPermi('system:barcode:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizBarcode bizBarcode)
    {
        supplierContext.resolveCurrentSupplierCode().ifPresent(bizBarcode::setSupplierCode);
        startPage();
        java.util.List<BizBarcode> list = bizBarcodeService.selectBizBarcodeList(bizBarcode);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('system:barcode:query')")
    @GetMapping(value = "/{barcodeId}")
    public AjaxResult getInfo(@PathVariable("barcodeId") Long barcodeId)
    {
        return success(bizBarcodeService.selectBizBarcodeByBarcodeId(barcodeId));
    }

    @PreAuthorize("@ss.hasPermi('system:barcode:add')")
    @Log(title = "箱码列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizBarcode bizBarcode)
    {
        return toAjax(bizBarcodeService.insertBizBarcode(bizBarcode));
    }

    @PreAuthorize("@ss.hasPermi('system:barcode:edit')")
    @Log(title = "箱码列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizBarcode bizBarcode)
    {
        return toAjax(bizBarcodeService.updateBizBarcode(bizBarcode));
    }

    @PreAuthorize("@ss.hasPermi('system:barcode:generate')")
    @Log(title = "生成箱码", businessType = BusinessType.INSERT)
    @PostMapping("/generate")
    public AjaxResult generate(@RequestBody GenerateBarcodeRequest request) {
        int rows = bizBarcodeService.generateBarcodes(request);
        java.util.Map<String, Object> data = new java.util.HashMap<>();
        data.put("rows", rows);
        data.put("batchNo", request.getBatchNo());
        return success(data);
    }

    // 新增：获取当日下个批次号，供前端弹窗展示
    @PreAuthorize("@ss.hasPermi('system:barcode:generate')")
    @GetMapping("/nextBatchNo")
    public AjaxResult nextBatchNo() {
        String batchNo = bizBarcodeService.getNextBatchNoForToday();
        java.util.Map<String, Object> data = new java.util.HashMap<>();
        data.put("batchNo", batchNo);
        return success(data);
    }
}
